package com.qq.rocketmq.factory;

import com.alibaba.fastjson.JSONObject;
import lombok.Builder;
import lombok.Data;
import org.apache.rocketmq.common.message.Message;
import org.springframework.util.CollectionUtils;
import java.util.Map;

import static com.alibaba.fastjson.util.IOUtils.UTF8;

/**
 * 消息生产类
 */
@Data
@Builder
public class MessageProduction<T> {
    private  String topic;

    private String  tag;

    private String messageKey;

    private T body;

    private Boolean isByTag = true;

    private Map<String ,String> userProperties;

    public static Message getMessage(MessageProduction production){
        Message message = new Message();
        if (production.getIsByTag()){
            message.setTags(production.getTag());
        }else{
            if (!CollectionUtils.isEmpty(production.getUserProperties())){
                Map<String,String> properties = production.getUserProperties();
                properties.forEach((k,v)->{
                    message.putUserProperty(k,v);
                });
            }
        }
        message.setKeys(production.getMessageKey());
        message.setBody(JSONObject.toJSONString(production.getBody()).getBytes(UTF8));
        return message;
    }
}
